package org.yidu.novel.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Service;
import org.yidu.novel.bean.ArticleSearchBean;
import org.yidu.novel.constant.YiDuConstants;
import org.yidu.novel.entity.TArticle;
import org.yidu.novel.entity.TSystemBlock;
import org.yidu.novel.repository.TArticleRepository;
import org.yidu.novel.repository.TSystemBlockRepository;
import org.yidu.novel.utils.Utils;

@Service
public class BlockService extends AbstractBaseService {

    @Autowired
    private TSystemBlockRepository systemBlockRepository;
    @Autowired
    private TArticleRepository articleRepository;

    /**
     * 根据页面类型取得相应的区块信息
     * 
     * <pre>
     * 1:主页
     * 2：小说列表
     * 3：小说介绍页
     * 4：小说阅读页
     * 11：登录页
     * 99：其他页
     * </pre>
     * 
     * @param page
     * 
     * @return 区块信息
     */
    @Cacheable(value = "yiduCache", key = "{'org.yidu.novel.service.BlockService.loadBlocks(short,String)', #target, #author }")
    public Map<String, Object> loadBlocks(short target, String author) {

        logger.debug(msg.getMessage("info.process.start", new String[] { "loadBlocks" }, Locale.getDefault()));
        // 区块信息
        Map<String, Object> blocks = new HashMap<String, Object>();

        List<TSystemBlock> systemBlockList = systemBlockRepository.findByTargetContainsOrderBySystemBlockNoAsc(target);

        systemBlockList.forEach(item -> {

            List<TArticle> articleList = null;
            Pageable pageable = null;
            int limitnum = item.getLimitNum() == null ? 1 : item.getLimitNum();

            switch (item.getType()) {
            case YiDuConstants.BlockType.ARTICLE_LIST:
                // 标准小说列表
                pageable = new PageRequest(0, limitnum, item.getIsAsc() ? Direction.ASC : Direction.DESC, item.getSortCol());
                ArticleSearchBean searchBean = new ArticleSearchBean();
                searchBean.setFullFlag(item.getIsFinish());
                searchBean.setCategory(item.getCategory());
                Page<TArticle> articles = articleRepository.findAllWithSearchBean(searchBean, pageable);

                articleList = articles.getContent();
                blocks.put(item.getBlockId(), articleList);

                break;
            case YiDuConstants.BlockType.CUSTONIZE_ARTICLE_LIST:
                // 自定义列表
                String[] articleNos = item.getContent().split(",");
                List<Long> articleNoList = new ArrayList<>();
                for (String s : articleNos) {
                    articleNoList.add(Long.valueOf(s));
                }
                articleList = articleRepository.findByArticleNoInAndLastChapterIsNotNull(articleNoList);
                blocks.put(item.getBlockId(), articleList);

                break;
            case YiDuConstants.BlockType.HTML:
                // HTML内容
                blocks.put(item.getBlockId(), item.getContent());
                break;
            case YiDuConstants.BlockType.RANDOM_LIST:

                // 随机推荐区块
                pageable = new PageRequest(0, limitnum);
                // articleList =
                // articleRepository.findRandomRecommendArticleList(pageable);
                // blocks.put(item.getBlockId(), articleList);

                break;
            case YiDuConstants.BlockType.RECOMMEND_LIST:

                // // 按小说分类和编号推荐区块
                // List<TArticle> articleList =
                // articleService.findRecommendArticleList(getRecommondCategory(),
                // getRecommondArticleno(), limitnum);
                // blocks.put(tSystemBlock.getBlockid(), articleList);

                break;
            case YiDuConstants.BlockType.RELATIVE_LIST:

                // // 相关小说区块（名字匹配）
                // String articleName = getRelativeArticleName();
                // if (StringUtils.isBlank(articleName)) {
                // // 小说名是空的话，直接跳过啦
                // continue;
                // }
                // List<String> keys = Utils.getKeyWords(articleName);
                // // 取相关小说
                // List<TArticle> articleList =
                // articleService.findRelativeArticleList(keys,
                // tSystemBlock.getSortcol(), tSystemBlock.getIsasc(),
                // tSystemBlock.getLimitnum());
                //
                // blocks.put(tSystemBlock.getBlockid(), articleList);

                break;
            case YiDuConstants.BlockType.SAME_AUTHOR_LIST:
                // 同作者区块
                if (!StringUtils.isBlank(author)) {
                    pageable = new PageRequest(1, limitnum, item.getIsAsc() ? Direction.ASC : Direction.DESC,
                            Utils.isDefined(item.getSortCol()) ? item.getSortCol() : "articleNo");
                    articleList = articleRepository.findByAuthorAndLastChapterIsNotNull(author, pageable).getContent();
                    blocks.put(item.getBlockId(), articleList);
                }
                break;
            }
        });

        // // 从缓存中把首页用的区块信息取出
        // blocks = new HashMap<String, Object>();
        // // 没有取到的话从数据库里取出
        // // block数据取得
        // List<TSystemBlock> blockList = new ArrayList<TSystemBlock>();
        // SystemBlockSearchBean searchBean = new SystemBlockSearchBean();
        // searchBean.setTargets(YiDuConstants.BlockTarget.ALL_SITE,
        // getBlockTarget());
        // blockList = systemBlockService.find(searchBean);
        // for (TSystemBlock tSystemBlock : blockList) {
        // int limitnum = tSystemBlock.getLimitnum() == null ? 1 :
        // tSystemBlock.getLimitnum();
        // if (tSystemBlock.getType() == YiDuConstants.BlockType.ARTICLE_LIST) {
        // ArticleSearchBean articleSearchBean = new ArticleSearchBean();
        // if (Utils.isDefined(tSystemBlock.getCategory())) {
        // articleSearchBean.setCategory(tSystemBlock.getCategory());
        // }
        // Pagination pagination = new Pagination(limitnum, 1);
        // pagination.setSortColumn(tSystemBlock.getSortcol());
        // pagination.setSortOrder(tSystemBlock.getIsasc() ? "ASC" : "DESC");
        // articleSearchBean.setPagination(pagination);
        // List<TArticle> articleList = articleService.find(articleSearchBean);
        // blocks.put(tSystemBlock.getBlockid(), articleList);
        // } else if (tSystemBlock.getType() ==
        // YiDuConstants.BlockType.RANDOM_LIST) {
        // // 随机推荐区块
        // List<TArticle> articleList =
        // articleService.findRandomRecommendArticleList(limitnum);
        // blocks.put(tSystemBlock.getBlockid(), articleList);
        //
        // } else if (tSystemBlock.getType() ==
        // YiDuConstants.BlockType.RECOMMEND_LIST) {
        // // 按小说分类和编号推荐区块
        // List<TArticle> articleList =
        // articleService.findRecommendArticleList(getRecommondCategory(),
        // getRecommondArticleno(), limitnum);
        // blocks.put(tSystemBlock.getBlockid(), articleList);
        //
        // } else if (tSystemBlock.getType() ==
        // YiDuConstants.BlockType.CUSTONIZE_ARTICLE_LIST) {
        // // 自定义小说列表
        // ArticleSearchBean articleSearchBean = new ArticleSearchBean();
        // articleSearchBean.setArticlenos(tSystemBlock.getContent());
        // List<TArticle> articleList = articleService.find(articleSearchBean);
        // // 为了维持和设置一样重新排序
        // List<TArticle> newArticleList = new ArrayList<TArticle>();
        // String[] articlenos = StringUtils.split(tSystemBlock.getContent(),
        // ",");
        // for (String no : articlenos) {
        // for (TArticle article : articleList) {
        // if (StringUtils.equals(no, String.valueOf(article.getArticleno()))) {
        // newArticleList.add(article);
        // // 减少循环次数，将已经取出的元素删掉
        // articleList.remove(article);
        // break;
        // }
        // }
        // }
        // blocks.put(tSystemBlock.getBlockid(), newArticleList);
        // } else if (tSystemBlock.getType() == YiDuConstants.BlockType.HTML) {
        // // HTML区块
        // blocks.put(tSystemBlock.getBlockid(), tSystemBlock.getContent());
        // } else if (tSystemBlock.getType() ==
        // YiDuConstants.BlockType.RELATIVE_LIST) {
        // // 相关小说区块（名字匹配）
        // String articleName = getRelativeArticleName();
        // if (StringUtils.isBlank(articleName)) {
        // // 小说名是空的话，直接跳过啦
        // continue;
        // }
        // List<String> keys = Utils.getKeyWords(articleName);
        // // 取相关小说
        // List<TArticle> articleList =
        // articleService.findRelativeArticleList(keys,
        // tSystemBlock.getSortcol(), tSystemBlock.getIsasc(),
        // tSystemBlock.getLimitnum());
        //
        // blocks.put(tSystemBlock.getBlockid(), articleList);
        // } else if (tSystemBlock.getType() ==
        // YiDuConstants.BlockType.SAME_AUTHOR_LIST) {
        // // 同作者区块
        // String author = getAuthor();
        // if (StringUtils.isBlank(author)) {
        // // 作者名是空的话，直接跳过啦
        // continue;
        // }
        // ArticleSearchBean articleSearchBean = new ArticleSearchBean();
        // articleSearchBean.setAuthor(author);
        // Pagination pagination = new Pagination(limitnum, 1);
        // pagination.setSortColumn(tSystemBlock.getSortcol());
        // pagination.setSortOrder(tSystemBlock.getIsasc() ? "ASC" : "DESC");
        // articleSearchBean.setPagination(pagination);
        // List<TArticle> articleList = articleService.find(articleSearchBean);
        //
        // blocks.put(tSystemBlock.getBlockid(), articleList);
        // }
        // }
        // CacheManager.putObject(getBlockKey(), null, blocks);
        // }
        logger.debug(msg.getMessage("info.process.end.normal", new String[] { "loadBlocks" }, Locale.getDefault()));
        return blocks;
    }
}